package com.zhuss.order.processor.unuse;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.zhuss.bean.unit.order.TrainGroupBean;
import com.zhuss.bean.vo.order.order.DetailOrderVo;
import com.zhuss.enums.OrderStatus;
import com.zhuss.exception.DzcxException;
import com.zhuss.exception.ExceptionCode;
import com.zhuss.order.db.dao.ext.OrderDao;
import com.zhuss.order.db.dao.ext.OrderItemDao;
import com.zhuss.order.processor.OrderCheck;
import com.zhuss.product.db.dao.ext.TrainDao;
import com.zhuss.util.OrderUseMill;

public class OrderUnuse {
	
	public static void startUnuseDecrUsed(DetailOrderVo order, OrderCheck orderCheck, OrderDao orderDao, OrderItemDao orderItemDao, TrainDao trainDao, String name, Long userId, Integer targetOperation) throws DzcxException {
		if (!orderCheck.checkUnuse(order)) {
			return;
		}
		Long createTimeMill = order.getCreateTime().getTime();
		Long nowMill = System.currentTimeMillis();
		Long duringMill = nowMill - createTimeMill;
		Long haveMill = OrderUseMill.USE_MILL; // 15 分钟
		if (duringMill > haveMill) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					Date now = new Date();
					orderDao.cancelBatch(Arrays.asList(order.getOrderId()), OrderStatus.用户触发过期.key(), name, userId, now);
					orderItemDao.cancelBatch(Arrays.asList(order.getOrderId()), OrderStatus.用户触发过期.key(), name, userId, now);
					List<TrainGroupBean> trainList = orderItemDao.listTrain(Arrays.asList(order.getOrderId()));
					trainDao.unused(trainList);
				}
			}).start();
			throw new DzcxException(ExceptionCode.订单已过期);
		} else if (OrderStatus.未支付之前取消.sameKey(targetOperation)) {
			List<TrainGroupBean> trainList = orderItemDao.listTrain(Arrays.asList(order.getOrderId()));
			trainDao.unused(trainList);
		}
	}

}
